package com.fy.utilsproject;

import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.fy.utilsproject.fragments.AnimTestFragment;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private final static String TAG = "MainActivity";

    private String currentFragmentTag;
    private String lastFragmentTag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            AnimTestFragment animTestFragment = AnimTestFragment.newInstance("","");
            fragmentTransaction.add(R.id.fl_main_fragment_container, animTestFragment,AnimTestFragment.TAG);
            fragmentTransaction.commit();
            currentFragmentTag = AnimTestFragment.TAG;
        }
        initView();
    }

    private void initView() {
        findViewById(R.id.btn_main_parse_xml).setOnClickListener(this);
        findViewById(R.id.btn_main_anim).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_anim:
                lastFragmentTag = currentFragmentTag;
                currentFragmentTag = AnimTestFragment.TAG;
                switchFragment();
                break;
        }
    }

    /**
     * 切换fragment
     */
    private void switchFragment() {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment currentFragment = fragmentManager.findFragmentByTag(currentFragmentTag);
        Fragment lastFragment = fragmentManager.findFragmentByTag(lastFragmentTag);
        if (lastFragment != null)
            fragmentTransaction.hide(lastFragment);
        if (currentFragment != null)
            fragmentTransaction.show(currentFragment);
        fragmentTransaction.commit();
    }


}
